package handler

import (
	"gorm.io/gorm"
	"log"
	"org.knight/api"
	"org.knight/biz/repo"
	"org.knight/data"
	"time"
)

type SpecificationHandler struct {
	Repo *repo.DBRepository
}

func (handler *SpecificationHandler) HandleStart(c *api.Context) {

	spec := &data.Spec{Name: c.SpecName, Version: c.SpecVersion}
	db := handler.Repo.DB()

	db.Transaction(func(tx *gorm.DB) error {

		log.Printf("saving spec %v \n", spec)
		tx.Model(spec).Where(spec).First(spec)
		if spec.ID == 0 {
			//no record
			handler.Repo.Save(spec)

		} else {
			// has record
			// clear data cascade

			log.Println("try clear legacy data for spec", spec)
			tx.Raw("delete from labels where exists(select 1 from info_elements where spec_id=?", spec.ID)

			tx.Raw("delete from ie_specs where exists(select 1 from info_elements where spec_id=?", spec.ID)

			tx.Raw("delete from info_elements where spec_id=?", spec.ID)
		}

		c.SpecId = spec.ID
		return nil
	})

}

func  (handler *SpecificationHandler) HandleEnd(c *api.Context) {
	log.Println("Spec handler ended at ", time.Now())
}
